<?php
/**
 * Created by PhpStorm.
 * User: worry
 * Date: 2016/12/29
 * Time: 19:14
 */

namespace backend\services;


use backend\models\validators\UserModifyPass;
use common\components\Error;
use common\helps\Func;
use common\models\User;
use common\services\BasicService;
use Yii;

class UserService extends BasicService
{

    /**
     * 登录
     * @param array $data
     * @param string $sessionKey
     * @return bool
     * @throws \Exception
     * @throws \yii\db\StaleObjectException
     */
    public function login($data = [], $sessionKey = 'user')
    {
        $userInfo = User::find()->where(['username' => $data['account']])->one();
        if (!$userInfo) {
            Error::exception('用户不存在', Error::USER_NOT_EXISTS);
        }
        if (!isset($data['pass']) || !$data['pass'] || $userInfo->password_hash != Func::password($data['pass'])) {
            Error::exception('密码不正确', Error::PASS_ERROR);
        }
        $userInfo->login_ip = $_SERVER['REMOTE_ADDR'];
        $userInfo->login_time = time();
        $rs = $userInfo->update();

        if ($rs) {
            Yii::$app->session->set($sessionKey, $userInfo->toArray());
            Yii::$app->user->login($userInfo, 3600 * 24);
            return true;
        } else {
            Error::exception('登录失败:' . $userInfo->getFirstErrors());
        }
    }


    /**
     * 判断是否登录
     * @param string $sessionKey
     * @return bool
     */
    public function isLogin($sessionKey = 'user')
    {
        $userInfo = Yii::$app->session->get($sessionKey);
        if (is_array($userInfo)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 列表页数据处理
     * @param $info
     * @param array $col
     * @return array
     */
    public function tableHanding($info, $col = [])
    {
        $info['login_time'] = $info['login_time'] ? date('Y-m-d H:i:s', $info['login_time']) : '';//创建时间格式化
        $res = [];
        //没有则直接按顺序直接返回数据
        foreach ($col as $field) {
            if (isset($info[$field])) {
                $res[] = $info[$field];
            } else if ($field == '_') {
                $res[] = $this->getTableActions($info);
            } else {
                $res[] = '';
            }
        }

        return $res;
    }

    /**
     * 保存数据之前的操作
     * @param $data
     * @param int $mode
     * @param array $oldData
     * @return bool
     * @throws \Exception
     */
    public function beforeSave(&$data, $mode = self::CREATE, $oldData = [])
    {
        //添加时验证密码
        if (!isset($data['id']) || !$data['id']) {
            if (!Func::validatePassword($data['password_hash'], $data['repass'])) {
                Error::exception('密码不能为空且必须一致');
            }
            $data['password_hash'] = Func::password($data['password_hash']);
        }
        $this->model->rules();
        //验证邮箱
        if ($data['email'] && !Func::validateEmail($data['email'])) {
            Error::exception('邮箱验证失败');
        }
        return true;
    }

    /**
     * 注销
     * @param string $key session key
     * @return bool
     */
    public function logout($key = 'admin')
    {
        Yii::$app->session->offsetUnset($key);
        return true;
    }


    /**
     * 修改密码
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function modifyPass($data = [])
    {
        $validate = new UserModifyPass();
        $validate->load($data, 'User');
        $error = self::getError($validate);
        if ($error) {
            Error::exception($error, 'VALIDATE_FAILED');
        }
        $model = User::findOne($validate->id);
        if (!$model) {
            Error::exception('用户不存在', 'MEMBER_NOT_EXISTS');
        }
        if ($model->password_hash != Func::password($validate->old_password_hash)) {
            Error::exception('密码错误');
        }
        $model->password_hash = Func::password($validate->password_hash);
        $rs = $model->save();
        if ($rs === false) {
            throw new \Exception(self::getError($model), 'SAVE_FAILED');
        }
        return true;
    }


}